import logging
from functools import wraps

from .views import make_problem_response
from .exceptions import FLeagueError, NotFoundError

log = logging.getLogger(__name__)


# Error Formatter
def errorfmt(e):
    title, status, detail = e.title, e.status, e.detail
    if e.args:
        if isinstance(e.args[0], int):
            status = e.args[0]
        detail = '#'.join(e.args)
    error = {
        'title': title,
        'status': status,
        'detail': detail,
        'type': type(e),
    }
    return make_problem_response(*args, **kwargs)


# Error Handler
def errorhandler(lastfn=None):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except NotFoundError as e:
                return '', 404
            except FLeagueError as e:
                log.error('Exception: %r', e)
                return errorfmt(e)  # problem Response
        return wrapper
    return decorator
